package br.com.news.activity;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import br.com.news.R;
import br.com.news.exception.ServiceException;
import br.com.news.modal.NoticiaBean;
import br.com.news.service.NoticiaService;
import br.com.news.service.interfaces.INoticiaService;
import br.com.news.util.Constantes;

public class ListNoticiaFragment extends ListFragment implements Runnable {

	public static final String ID_CATEGORIA = "id_categoria";

	private List<NoticiaBean> noticiaBeans;
	private long idCategoria;
	private INoticiaService noticiaService;
	private NoticiaAdapter noticiaAdapter;
	private long idUltimaNoticia;
	private long idPrimeiraNoticia;
	private boolean primeiraExecucao = false;

	private Handler handler;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		handler = new Handler();
		return inflater.inflate(R.layout.activity_list_noticia, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		primeiraExecucao = true;
		noticiaService = new NoticiaService(getActivity());
		reculperaParametros();
		preencherNoticias();
		defineAcoes();
	}

	private void defineAcoes() {
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (noticiaAdapter.isMaisNoticia() && position == noticiaBeans.size() - 1) {
					int pos = getListView().getFirstVisiblePosition();
					carregaListaNoticia(false, true, false);
					getListView().setSelectionFromTop(pos, 0);
					new Thread(ListNoticiaFragment.this).start();
				} else {
					NoticiaBean noticiaBean = noticiaBeans.get(position);
					Intent intent = new Intent(getActivity(), NoticiaActivity.class);
					intent.putExtra(Constantes.ID_NOTICIA, noticiaBean.getId());
					getActivity().startActivity(intent);
				}
			}
		});

	}

	private void reculperaParametros() {
		Bundle bundle = getArguments();
		if (bundle != null) {
			idCategoria = bundle.getLong(ID_CATEGORIA);
		}
	}

	private void preencherNoticias() {
		try {
			if (noticiaBeans == null) {
				noticiaBeans = noticiaService.findNoticiaByIdCategoria(idCategoria);
			}
			if (noticiaBeans.isEmpty()) {
				noticiaBeans.add(new NoticiaBean());
				idUltimaNoticia = 0;
				carregaListaNoticia(true, false, false);
				new Thread(this).start();
			} else {
				idUltimaNoticia = noticiaBeans.get(noticiaBeans.size() - 1).getId();
				noticiaBeans.add(new NoticiaBean());
				carregaListaNoticia(false, false, true);
			}
		} catch (ServiceException e) {
			ErroActivity.chamaActivityErro(ListNoticiaFragment.this.getActivity(), R.string.falha_apresentar_noticia);
			ListNoticiaFragment.this.getActivity().finish();
		}
	}

	private void carregaListaNoticia(boolean caregandoInicio, boolean carregandoFim, boolean maisNoticia) {
		noticiaAdapter = new NoticiaAdapter(getActivity(), R.layout.activity_item_list_noticia, noticiaBeans, caregandoInicio, carregandoFim, maisNoticia);
		setListAdapter(noticiaAdapter);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (noticiaService != null) {
			noticiaService.fechar();
		}
	}

	@Override
	public void run() {
		try {
			noticiaService.sincronizaNoticiasAnteriores(idUltimaNoticia, idCategoria);
			handler.post(new Runnable() {
				@Override
				public void run() {
					try {
						int posicao = getListView().getFirstVisiblePosition();
						noticiaBeans = noticiaService.findNoticiaByIdCategoria(idCategoria);
						if (!noticiaBeans.isEmpty()) {
							ListNoticiaFragment.this.idUltimaNoticia = noticiaBeans.get(noticiaBeans.size() - 1).getId();
							noticiaBeans.add(new NoticiaBean());
						}
						carregaListaNoticia(false, false, true);
						if (posicao > 0) {
							getListView().setSelection(posicao);
						}
						if (primeiraExecucao) {
							primeiraExecucao = false;
							atualizaNoticias();
						}
					} catch (ServiceException e) {
						Log.e(Constantes.LOG, e.getMessage(), e);
						if (getActivity() != null && !getActivity().isFinishing()) {
							ErroActivity.chamaActivityErro(getActivity(), R.string.nenhuma_categoria_selecionada);
							getActivity().finish();
						}
					}
				}
			});
		} catch (Exception e) {
			Log.e(Constantes.LOG, e.getMessage(), e);
			handler.post(new Runnable() {
				@Override
				public void run() {
					if (getActivity() != null && !getActivity().isFinishing()) {
						ErroActivity.chamaActivityErro(getActivity(), R.string.falha_sincronizar_noticia);
						getActivity().finish();
					}
				}
			});
		}
	}

	private void atualizaNoticias() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(15000);
						handler.post(new Runnable() {
							@Override
							public void run() {
								try {
									int posicao = getListView().getFirstVisiblePosition();
									int size = noticiaBeans.size();
									noticiaBeans = noticiaService.findNoticiaByIdCategoria(idCategoria);
									if (!noticiaBeans.isEmpty()) {
										ListNoticiaFragment.this.idPrimeiraNoticia = noticiaBeans.get(0).getId();
										noticiaBeans.add(new NoticiaBean());
									}
									carregaListaNoticia(false, false, true);
									getListView().setSelection((posicao + noticiaBeans.size()) - size);
								} catch (Exception e) {
									Log.e(Constantes.LOG, e.getMessage(), e);
								}
							}
						});

					} catch (Exception e) {
						Log.e(Constantes.LOG, e.getMessage(), e);
					}
				}
			}
		}).start();
	}
}
